package com.yuyang.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.yuyang.common.constant.AuthServerConstants;
import com.yuyang.common.exception.BizCodeEnum;
import com.yuyang.common.utils.R;
import com.yuyang.common.vo.MemberResponseVo;
import com.yuyang.gulimall.auth.feign.MemberFeignServer;
import com.yuyang.gulimall.auth.feign.ThirdPartFeignService;
import com.yuyang.gulimall.auth.to.UserLoginTo;
import com.yuyang.gulimall.auth.to.UserRegisterTo;
import com.yuyang.gulimall.auth.vo.UserLoginVo;
import com.yuyang.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author yu yang
 * @date 2023/1/19 -18:15
 */
@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ThirdPartFeignService thirdPartFeignService;
    @Autowired
    MemberFeignServer memberFeignServer;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //验证码为空
        if (StringUtils.isBlank(phone)){
            return R.error(BizCodeEnum.SMS_CODE_EXIST_EXEPTION.getCode(),BizCodeEnum.SMS_CODE_EXIST_EXEPTION.getMsg());
        }
        //接口防刷
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstants.SMS_CODE_CACHE_PRIFIX + phone);
        if (StringUtils.isNotBlank(s)) {
            String[] split = s.split("_");
            if (System.currentTimeMillis() - Long.parseLong(split[1]) < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXEPTION.getCode(), BizCodeEnum.SMS_CODE_EXEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        thirdPartFeignService.sendCode(phone, code);
        stringRedisTemplate.opsForValue().set(AuthServerConstants.SMS_CODE_CACHE_PRIFIX + phone, code + "_" + System.currentTimeMillis(), 5, TimeUnit.MINUTES);
        return R.ok();
    }

    //TODO 分布式下ssesion共享问题
    @PostMapping("/register")
    public String register(@Valid UserRegistVo userRegistVo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {

        //数据格式校验
        if (bindingResult.hasErrors()) {
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //验证码校验
        String code = stringRedisTemplate.opsForValue().get(AuthServerConstants.SMS_CODE_CACHE_PRIFIX + userRegistVo.getPhone());
        if (StringUtils.isNotBlank(code) && userRegistVo.getCode().equalsIgnoreCase(code.split("_")[0])) {
            //注册用户
            UserRegisterTo userRegisterTo = new UserRegisterTo();
            BeanUtils.copyProperties(userRegistVo, userRegisterTo);
            R r = memberFeignServer.register(userRegisterTo);
            //注册成功
            if (r.getCode() == 0) {
                stringRedisTemplate.delete(AuthServerConstants.SMS_CODE_CACHE_PRIFIX + userRegistVo.getPhone());
                return "redirect:http://auth.gulimall.com/login.html";
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", r.getData("msg", new TypeReference<String>() {
                }));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

    }
    @PostMapping("login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        UserLoginTo userLoginTo = new UserLoginTo();
        BeanUtils.copyProperties(vo,userLoginTo);
        R login = memberFeignServer.login(userLoginTo);
        //登录成功
        if (login.getCode() == 0){
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {
            });
            //放到session中
            session.setAttribute(AuthServerConstants.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        if (session.getAttribute(AuthServerConstants.LOGIN_USER) == null){
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }
    }


}
